﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using ZX.Common.Extend;
using ZX.BLL.Extend;
using System.Threading.Tasks;
using System.Data;
using ZX.EHR.Library;
using System.Text;
using ZX.Web.UI.Controls;

namespace ZX.WebApp.Crm.Hodometer
{
    public partial class InnerCalendar : ListPage
    {
        private string sb
        {
            get
            {
                if (ViewState["sb"] == null)
                    return "";
                else
                    return ViewState["sb"].ToString();
            }
            set
            {
                ViewState["sb"] = value;
            }
        }
        public string RebackDate
        {
            get { return DateTime.Now.ToShortDateString(); }
        }
        System.Globalization.Calendar calender = System.Globalization.CultureInfo.InvariantCulture.Calendar;
        private int year //定义年的变量的初始值
        {
            get
            {
                if (ViewState["Year"] != null)
                {
                    if (int.Parse(ViewState["Year"].ToString()) > 9999 && int.Parse(ViewState["Year"].ToString()) < 1000)
                    {
                        return DateTime.Now.Year;
                    }
                    else
                    {
                        return int.Parse(ViewState["Year"].ToString());
                    }

                }
                else
                {
                    return DateTime.Now.Year;
                }
            }
            set
            {
                ViewState["Year"] = value;
            }
        }
        private int month       //定义月的变量的初始值
        {
            get
            {
                if (ViewState["Month"] != null)
                {
                    if (int.Parse(ViewState["Month"].ToString()) < 0 && int.Parse(ViewState["Month"].ToString()) >= 13)
                    {
                        return DateTime.Now.Month;
                    }
                    else
                    {
                        return int.Parse(ViewState["Month"].ToString());
                    }
                }
                else
                {
                    return DateTime.Now.Month;
                }
            }
            set
            {
                ViewState["Month"] = value;
            }
        }
        private int day           //定义日的变量的初始值
        {
            get
            {
                if (ViewState["Day"] != null)
                {
                    if (int.Parse(ViewState["Day"].ToString()) < 0 && int.Parse(ViewState["Day"].ToString()) > 31)
                    {
                        return DateTime.Now.Day;
                    }
                    else
                    {
                        return int.Parse(ViewState["Day"].ToString());
                    }
                }
                else
                {
                    return DateTime.Now.Day;
                }
            }
            set
            {
                ViewState["Day"] = value;
            }
        }

        //传进来的讲师
        private string RequestTea
        {
            get
            {
                if (ViewState["Retea"] != null)
                {
                    return ViewState["Retea"].ToString();
                }
                else
                {
                    return "";
                }
            }
            set
            {
                ViewState["Retea"] = value;
            }
        }
        //选择的讲师
        public string SelectTea
        {
            get
            {
                if (ViewState["Setea"] != null)
                {
                    return ViewState["Setea"].ToString();
                }
                else
                {
                    string SeteaFromPage = Request["Setea"];
                    if (SeteaFromPage != null && !SeteaFromPage.Equals(string.Empty))
                    {
                        ViewState["Setea"] = SeteaFromPage;
                        return SeteaFromPage;
                    }
                    else
                    {
                        return "";
                    }
                }

            }
            set
            {
                ViewState["Setea"] = value;
            }
        }
        //选择的讲师
        private string TeaName
        {
            get
            {
                if (ViewState["TeaName"] != null)
                {
                    return ViewState["TeaName"].ToString();
                }
                else
                    return "";

            }
            set
            {
                ViewState["TeaName"] = value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // 权限 
            if (this.UserId == null)
            {
                Response.Redirect("/Error.aspx?message=1&functionId=" + FunctionID);
                return;
            }
            if (!CheckFunctionRight())
            {
                Response.Redirect("/Error.aspx?message=2&functionId=" + FunctionID);
                return;
            }
            if (!this.IsPostBack)
            {
                SelectTea = RequestTea = Request.QueryString["TEAID"];
                bl_DataBind();
            }

        }
        /// <summary>
        /// 绑定推广讲师
        /// </summary>
        private void bl_DataBind()
        {
            List<ZX.CRM.Library.V_GetUserByPositions> vu = GetTeacher();
            if (vu != null)
            {
                blInnerTeacher.DataSource = vu;
                blInnerTeacher.DataTextField = "UName";
                blInnerTeacher.DataValueField = "UserID";
                blInnerTeacher.DataBind();
                if (SelectTea == "")
                {
                    SelectTea = vu[0].UserID.ToString();
                    TeaName = vu[0].UName;

                }
                else
                {
                    TeaName = vu.Where(p => p.UserID.ToString() == SelectTea).First().UName;
                }

            }
            dl_DataBind();
        }
        private void dl_DataBind()
        {
            string teachid = SelectTea;
            if (teachid == "")
            {
                return;
            }
            DateTime dt = new DateTime(year, month, 1);
            int w = (int)dt.DayOfWeek;

            int daysInMonth = calender.GetDaysInMonth(year, month);
            ArrayList date = new ArrayList();          //定义日历展示用的数组
            for (int i = 0; i < w; i++)
            {
                date.Add(0);
            }
            for (int i = 0; i < daysInMonth; i++)
                date.Add(i + 1);

            dl_Calendar.DataSource = GetDtByPara(date, GetV_CrmTeachHodometerList(teachid));
            dl_Calendar.DataBind();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Review", "ReviewForm('" + sb + "')", true);
        }
        //整合数据源
        protected DataTable GetDtByPara(ArrayList date, IList<ZX.CRM.Library.V_CRMInnerTeachhoder> vcthl)
        {
            DataTable dt = new DataTable();
            #region 创建新列、定义汇总数
            DataColumn dc1 = new DataColumn("DTime", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("ID", Type.GetType("System.String"));
            DataColumn dc3 = new DataColumn("Cusid", Type.GetType("System.String"));
            DataColumn dc4 = new DataColumn("Cusname", Type.GetType("System.String"));
            DataColumn dc5 = new DataColumn("Nums", Type.GetType("System.String"));
            DataColumn dc6 = new DataColumn("BackColor", Type.GetType("System.String"));


            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);
            dt.Columns.Add(dc5);
            dt.Columns.Add(dc6);

            #endregion
            int nul = 1;
            foreach (int item in date)
            {
                DataRow dr = dt.NewRow();
                IList<ZX.CRM.Library.V_CRMInnerTeachhoder> vil = null;
                if (vcthl != null && item > 0 && item < 32)
                {
                    //if (vcthl[0].BeginDate >= Convert.ToDateTime(year.ToString() + "-" + month.ToString("D2") + "-" + item.ToString("D2"))) {
                    vil = vcthl.Where(V => Convert.ToDateTime(V.BeginDate.ToString("yyyy-MM-dd")) <= Convert.ToDateTime(year.ToString() + "-" + month.ToString("D2") + "-" + item.ToString("D2")) && Convert.ToDateTime(year.ToString() + "-" + month.ToString("D2") + "-" + item.ToString("D2")) <= V.EndDate).ToList<ZX.CRM.Library.V_CRMInnerTeachhoder>();
                    // }
                    // else
                    // {
                    //  vil = vcthl.Where(V => Convert.ToDateTime(V.BeginDate.ToString("yyyy-MM-dd")) <= Convert.ToDateTime(year.ToString() + "-" + month.ToString("D2") + "-" + item.ToString("D2")) && Convert.ToDateTime(year.ToString() + "-" + month.ToString("D2") + "-" + item.ToString("D2")) <= V.EndDate).ToList<ZX.CRM.Library.V_CRMInnerTeachhoder>();
                    // }
                }
                dt.Rows.Add(AddRow(nul, dr, item, vil));//.Where(p=>p.Sex ==True)
                nul++;
            }
            return dt;
        }

        //行赋值
        protected DataRow AddRow(int nul, DataRow dr, int dtime, IList<ZX.CRM.Library.V_CRMInnerTeachhoder> va)
        {
            dr["Nums"] = nul;
            if (dtime == 0)
            {
                dr["DTime"] = nul.ToString() + nul.ToString() + "0";
                dr["ID"] = "";
                dr["Cusid"] = "";
                dr["Cusname"] = "";
                dr["BackColor"] = "White";
            }
            else
            {
                dr["DTime"] = dtime;
                if (va != null && va.Count != 0)
                {
                    dr["ID"] = va[0].ID;
                    if (va[0].BeginDate == va[0].EndDate) { dr["Cusname"] = va[0].Reason; }
                    else
                    {
                        dr["Cusname"] = va[0].CustomerName + "</br>(" + va[0].BeginDate.ToString("HH:mm") + "--" + va[0].EndDate.ToString("HH:mm") + ")</br>" + va[0].Reason;
                    }
                    dr["Cusid"] = va[0].CustomerId;
                    dr["BackColor"] = va[0].backcolor;
                }
                else
                {
                    dr["ID"] = "";
                    dr["Cusname"] = "";
                    dr["Cusid"] = "";
                    dr["BackColor"] = "White";

                }

            }
            return dr;
        }
        protected void blInnerTeacher_OnClick(object sender, BulletedListEventArgs e)
        {
            ListItem li = blInnerTeacher.Items[e.Index];
            SelectTea = li.Value;
            TeaName = li.Text;
            dl_DataBind();
        }

        protected IList<ZX.CRM.Library.V_CRMInnerTeachhoder> GetV_CrmTeachHodometerList(string tchid)
        {
            ZX.CRM.Library.V_CRMInnerTeachhoder vcth = new ZX.CRM.Library.V_CRMInnerTeachhoder();
            BaseBussnies bvcth = new BaseBussnies(vcth);
            IList<ZX.CRM.Library.V_CRMInnerTeachhoder> vcthl = bvcth.GetEntitys<ZX.CRM.Library.V_CRMInnerTeachhoder>(" TeachID='" + tchid + "' and  (YEAR(BeginDate) = '" + year + "' or YEAR(BeginDate) = '" + year + "')AND (MONTH(BeginDate) = '" + month + "' or MONTH(BeginDate) = '" + month + "')");
            return vcthl;
        }
        /// <summary>
        /// 替换HTML标签</br>
        /// </summary>
        /// <param name="obj">字符串</param>
        /// <returns></returns>
        public string getReplace(object obj)
        {
            return obj == null ? "" : obj.ToString().Replace("</br>", "\n");
        }

        /// <summary>
        /// 截取长字符串</br>
        /// </summary>
        /// <param name="obj">字符串</param>
        /// <returns></returns>
        public string getShortName(object obj)
        {
            string strObj = "", strReturn = "";
            string[] strArr;
            strObj = obj == null ? "" : obj.ToString();
            strArr = strObj.Split('<');
            for (int i = 0; i < strArr.Length; i++)
            {
                if (i == 0 && strArr[i].Length > 15)
                {
                    strReturn = strReturn + strArr[i].Substring(0, 15) + "...<";
                }
                else
                {
                    if (i == strArr.Length - 1)
                    {
                        strReturn = strReturn + strArr[i];
                    }
                    else { strReturn = strReturn + strArr[i] + "<"; }
                }
            }

            return strReturn;
        }
        protected void dl_Command(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Pre":
                    if (month == 1)
                    {
                        year = year - 1;
                        month = calender.GetMonthsInYear(year);
                    }
                    else
                    {
                        month = month - 1;
                    }
                    dl_DataBind();
                    break;

                case "PreY":
                    year = year - 1;
                    dl_DataBind();
                    break;

                case "Next":
                    if (month == calender.GetMonthsInYear(year))
                    {
                        year = year + 1;
                        month = 1;
                    }
                    else
                    {
                        month = month + 1;
                    }
                    dl_DataBind();
                    break;
                case "NextY":
                    year = year + 1;
                    dl_DataBind();
                    break;
            }
        }
        protected void dl_Calendar_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                Label lab_Time = (Label)e.Item.FindControl("lab_Time");
                lab_Time.Text = year + "-" + month;

                Label labt = (Label)e.Item.FindControl("Labteacher");
                labt.Text = TeaName;
            }
        }
        //获取讲师
        protected List<ZX.CRM.Library.V_GetUserByPositions> GetTeacher()
        {
            ZX.CRM.Library.V_GetUserByPositions vgubp = new ZX.CRM.Library.V_GetUserByPositions();
            BaseBussnies bgubp = new BaseBussnies(vgubp);

            bgubp.Order = "LoginName";
            bgubp.Desc = "No";
            IList<ZX.CRM.Library.V_GetUserByPositions> Ivl = bgubp.GetEntitys<ZX.CRM.Library.V_GetUserByPositions>(" (PositionName ='内训讲师部讲师' or PositionName = '内训讲师部总经理') and isexpire=0");
            if (Ivl != null)
            {
                return Ivl.ToList<ZX.CRM.Library.V_GetUserByPositions>();
            }
            else
            {
                List<ZX.CRM.Library.V_GetUserByPositions> vgubpl = null;
                return vgubpl;
            }
        }

        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public string getRoleCondition()
        {
            IList<ZX.EHR.Library.SysRoleFunction> list = (new ZX.BLL.BUser()).GetRoleFunction(this.UserId, this.FunctionID);
            string strCondition = "";

            if (list == null)
            {
                return "";
            }
            foreach (var entity in list)
            {
                switch (entity.OperateRangeType.Trim())
                {
                    ///只能查看本人数据
                    case "0":
                        strCondition = "0" + this.User.UName;
                        break;
                    ///可以看本部门的
                    case "1":
                        strCondition = "1" + this.User.UName;
                        return strCondition;
                    //break;
                    //// 全部数据
                    //case "2":
                    //    break;
                    ////自定义部门条件
                    //case "3":
                    //    // 如果自定义条件
                    //    if (strCondition.ToString() != "")
                    //    {
                    //        strCondition.Append(" OR ");
                    //    }
                    //    strCondition.Append(string.Format(" UserID in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                    //    break;
                    //// 自定义条件数据
                    //case "4":
                    //    if (strCondition.ToString() != "")
                    //    {
                    //        strCondition.Append(" OR ");
                    //    }
                    //    if (entity.Condition != string.Empty)
                    //    {
                    //        strCondition.Append(" " + entity.Condition + " ");
                    //    }
                    //    break;
                    default:
                        strCondition = "1" + this.User.UName;
                        return strCondition;
                    //break;
                }
            }

            return strCondition;
        }

    }
}